package main

import (
	"fmt"
	"time"

	"gitee.com/daysleep/wechatBot/bot"
	"gitee.com/daysleep/wechatBot/tool"
)

func main() {
	bot := bot.GetNewBot()
	uuid, err := bot.GetUuid()
	if err != nil {
		panic(err)
	}
	fmt.Println(uuid)
	bot.GenQRcode(uuid)
	loginurl := bot.Login(uuid)
	info := bot.LoginInfo(loginurl)
	initstr := bot.WebwxInit(info.Pass_ticket, info.Wxuin, info.Wxsid, info.Skey)
	synckey, sk := tool.GetSynckey(initstr)
	me := tool.GetMe(initstr)
	userStr := bot.GetAllUsers(info.Skey)
	usersList := tool.GetUsers(userStr)
	usersList.UserList = append(usersList.UserList, &me)
	fmt.Println("usersList:")
	for _, v := range usersList.UserList {
		fmt.Println(v)
	}
	var allMsg map[string]*tool.MsgInfo = make(map[string]*tool.MsgInfo)
	go func() {
		var to, msg string
		for {
			fmt.Scan(&to, &msg)
			_to := usersList.GetUserName(to)
			if _to != "" {
				bot.SendMsg(info.Wxuin, info.Wxsid, info.Skey, info.Pass_ticket, msg, usersList.GetUserName("我"), _to)
				fmt.Println("send success")
			} else {
				fmt.Println("err to")
			}
		}
	}()
	for {
		retcode, _ := bot.SyncCheck(info.Wxuin, info.Wxsid, info.Skey, synckey)
		switch retcode {
		case "0":
			wxSync := bot.WebwxSync(info.Wxuin, info.Wxsid, info.Skey, info.Pass_ticket, sk)
			msg := tool.GetMsg(wxSync)
			for _, v := range msg {
				_, ok := allMsg[v.MsgId]
				if !ok {
					allMsg[v.MsgId] = v
					if v.MsgType == 1 {
						fmt.Printf("from:%v,to:%v,says:%v\n", usersList.GetName(v.FromUserName), usersList.GetName(v.ToUserName), v.Content)
					}
				}
			}
		case "1100":
			fmt.Println("失败/登出微信")
			return

		case "1101":
			fmt.Println("从其它设备登录微信网页版")
			return

		default:
			fmt.Println("异次元通信")
			return
		}
		time.Sleep(time.Second * 3)
	}
}
